package kt_test.ui.fragment

import java.text.SimpleDateFormat
import java.util.Locale
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.example.healthapp.R
import kt_test.room.entity.OxygenSampleEntity
import kt_test.viewmodel.OxygenSampleViewModel
import org.json.JSONArray
import java.io.File
import java.io.FileWriter
import java.util.*

class OxygenQueryFragment : Fragment() {

    private lateinit var inputUserId: EditText
    private lateinit var btnStartTime: Button
    private lateinit var btnEndTime: Button
    private lateinit var tvSelectedTime: TextView
    private lateinit var btnQuery: Button
    private lateinit var btnExportJson: Button
    private lateinit var btnExportCsv: Button

    private var startTime: String? = null
    private var endTime: String? = null

    private val viewModel: OxygenSampleViewModel by viewModels()
    private var currentSamples: List<OxygenSampleEntity> = emptyList()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.fragment_oxygen_query, container, false)

        inputUserId = view.findViewById(R.id.et_user_id)
        btnStartTime = view.findViewById(R.id.btn_start_time)
        btnEndTime = view.findViewById(R.id.btn_end_time)
        tvSelectedTime = view.findViewById(R.id.tv_selected_time)
        btnQuery = view.findViewById(R.id.btn_query)
        btnExportJson = view.findViewById(R.id.btn_export_json)
        btnExportCsv = view.findViewById(R.id.btn_export_csv)

        btnStartTime.setOnClickListener {
            showDateTimePicker { selected ->
                startTime = selected
                updateSelectedTime()
            }
        }

        btnEndTime.setOnClickListener {
            showDateTimePicker { selected ->
                endTime = selected
                updateSelectedTime()
            }
        }

        btnQuery.setOnClickListener {
            val userId = inputUserId.text.toString().ifBlank { null }
            val chartFragment = OxygenChartFragment.newInstance(userId, startTime, endTime)

            parentFragmentManager.beginTransaction()
                .replace(R.id.main_fragment, chartFragment)
                .addToBackStack(null)
                .commit()
        }

        btnExportJson.setOnClickListener {
            exportSamplesToJson()
        }

        btnExportCsv.setOnClickListener {
            exportSamplesToCsv()
        }

        viewModel.samples.observe(viewLifecycleOwner, Observer { list ->
            currentSamples = list
        })

        return view
    }

    private fun updateSelectedTime() {
        tvSelectedTime.text = getString(R.string.
         time_range_format, startTime ?: "未选", endTime ?: "未选")
    }

    private fun showDateTimePicker(onTimeSelected: (String) -> Unit) {
        val calendar = Calendar.getInstance()
        DatePickerDialog(requireContext(), { _, year, month, day ->
            TimePickerDialog(requireContext(), { _, hour, minute ->
                val timeStr = String.format("%04d-%02d-%02d %02d:%02d:00", year, month + 1, day, hour, minute)
                onTimeSelected(timeStr)
            }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true).show()
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show()
    }

    private fun exportSamplesToJson() {
        if (currentSamples.isEmpty()) {
            Toast.makeText(requireContext(), "暂无数据可导出", Toast.LENGTH_SHORT).show()
            return
        }
        try {
            val jsonArray = JSONArray()
            for (sample in currentSamples) {
                val obj = org.json.JSONObject()
                obj.put("time", sample.time)
                obj.put("spo2", sample.spo2)
                jsonArray.put(obj)
            }
            val outputDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            val file = File(outputDir, "oxygen_data_${System.currentTimeMillis()}.json")
            file.writeText(jsonArray.toString(2))
            Toast.makeText(requireContext(), "JSON导出成功：${file.absolutePath}", Toast.LENGTH_LONG).show()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(requireContext(), "导出失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun exportSamplesToCsv() {
        if (currentSamples.isEmpty()) {
            Toast.makeText(requireContext(), "暂无数据可导出", Toast.LENGTH_SHORT).show()
            return
        }
        try {
            val outputDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            val file = File(outputDir, "oxygen_data_${System.currentTimeMillis()}.csv")
            val writer = FileWriter(file)
            writer.append("time,spo2\n")
            for (sample in currentSamples) {
                writer.append("${sample.time},${sample.spo2}\n")
            }
            writer.flush()
            writer.close()
            Toast.makeText(requireContext(), "CSV导出成功：${file.absolutePath}", Toast.LENGTH_LONG).show()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(requireContext(), "导出失败", Toast.LENGTH_SHORT).show()
        }
    }
}